<?php

// $Id$

require_once(TANGRA_MAIN_DIR.'interfaces/i_db_storable.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/vpage/tcms_vpage_system_attribute_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/vpage/tcms_vpage_ci_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/vpage/tcms_vpt_system_attribute_dbc.class.php');


abstract class VPage_Abs_DBC extends Tangra_Class implements I_DB_Storable {
	private $vpage_id = 0;

	protected function load_system_attribute(DB_Connection $dbc, $vpage_id, $sa_export_name) {
		$rez = TCMS_VPage_System_Attribute_DBC::load_all_by_sa_export_name_vpage($dbc, $sa_export_name, $vpage_id);
		if (count($rez)) {
			$ret = current($rez);
		} else {
			$ret = false;
		}

		return $ret;
	}


	protected function load_content_item(DB_Connection $dbc, $vpage_id, $ci_export_name) {
		$ret = false;

		$ci = new TCMS_VPage_CI_DBC();
		if ($ci->load_ci_by_page_and_export_name($dbc, $vpage_id, $ci_export_name)) {
			$ret = $ci;
		}

		return $ret;
	}


	protected function save_system_attribute(DB_Connection $dbc, $vpage_id, $template_id, $sa_export_name, $value) {
		$sa = $this->load_system_attribute($dbc, $vpage_id, $sa_export_name);
		if (!$sa) {
			$vpt_sa = new TCMS_VPT_System_Attribute_DBC();
			if ($vpt_sa->load_by_template_and_export_name($dbc, $template_id, $sa_export_name)) {
				$sa = new TCMS_VPage_System_Attribute_DBC();
				$sa->set_t_sa_id($vpt_sa->get_id());
				$sa->set_vpage($vpage_id);
				$sa->set_value($value);
				$sa->save($dbc);
			}
		} else {
			if (trim($value)) {
				$sa->set_value($value);
				$sa->save($dbc);
			} else {
				$vpt_sa = new TCMS_VPT_System_Attribute_DBC();
				if ($vpt_sa->load_by_template_and_export_name($dbc, $template_id, $sa_export_name)) {
					if (!$vpt_sa->get_required()) {
						TCMS_VPage_System_Attribute_DBC::delete($dbc, $sa->get_id());
					}
				}
			}
		}
	}


	public function set_vpage_id($vpage_id) {
		tangra_if_not_int_throw_e($vpage_id);
		$this->vpage_id = $vpage_id;
	}


	public function get_vpage_id() {
		return $this->vpage_id;
	}


	public function set_id($id) {
		$this->set_vpage_id($id);
	}


	public function get_id() {
		return $this->get_vpage_id();
	}
}